package top.yxqz.servletcontext;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Enumeration;

/**
 * @author Mr.余
 * @date 2022/11/14
 * @package top.yxqz.servletcontext
 */
public class ServletContextDemo02 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ServletContext context  = getServletContext();
        //        解决中文乱码问题
        String req_encoding = context.getInitParameter("req_encoding");
        String resp_encoding = context.getInitParameter("resp_encoding");
        request.setCharacterEncoding(req_encoding);
        response.setContentType(resp_encoding);

        PrintWriter writer = response.getWriter();

        Enumeration<String> initParameterNames = context.getInitParameterNames();
        while (initParameterNames.hasMoreElements()){
            String key = initParameterNames.nextElement();
            String value = context.getInitParameter(key);
            writer.print("key："+key+"value："+value);
            writer.print("<hr>");
        }

//        getRealPath:获取真实路径（参数是，要查询的文件的相对路径）
        String realPath = context.getRealPath("/index.jsp");
        writer.print("<hr>");
        writer.print("index.jsp的真实路径："+realPath);

//        getContextPath：获取应用上下文路径
        String contextPath = context.getContextPath();
        writer.print("<hr>");
        writer.print("应用上下文是："+contextPath);

//        setAttribute：设置数据到域中
        String [] studentNames ={"刘备","张飞","关羽"};
        context.setAttribute("username",studentNames);

//        从域中得到数据，通过key
        String [] usernames = (String [])context.getAttribute("username"); //强转
        writer.print("<hr>");
        writer.print("学生的姓名："+ Arrays.toString(usernames));

//      删除域中的数据 通过key
        context.removeAttribute("username");
        String [] removed_usernames = (String [])context.getAttribute("username"); //强转
        writer.print("<hr>");
        writer.print("移除过后学生的姓名："+ Arrays.toString(removed_usernames));


    }
}
